<template>
    <div>
        <div>
            <el-button size="small" :disabled="props.disabled" @click="show">{{ props.label || '选择店铺' }}</el-button>
        </div>
        <el-tag
            v-for="(item, index) in stores"
            :key="item.name"
            class="store_item"
            :type="item.id"
            :closable="!props.disabled"
            @close="handleClose(item, index)">
            {{ item.name }}
        </el-tag>
        <ZwSelectStore
            ref="ZWStoreRef"
            :multiple="props.multiple"
            inline-tips="该店铺不支持同步订单"
            :is-disabled-line="isDisabledLine"
            @submit="submit">
            <template #header>
                <div v-if="props.tips" class="tips">注：仅支持同步客易达电商、有赞店铺在指定时间段内的用户数据</div>
            </template>
        </ZwSelectStore>
    </div>
</template>
<script setup lang="tsx">
import { reactive, ref, watch, computed } from 'vue';
import ZWStore from '@/components/ZWStore.vue';
import ZWGraphic from '@/components/ZWGraphic.vue';

interface Props {
    modelValue: string | string[];
    multiple: boolean;
    disabled: boolean;
    label: string;
    tips: boolean;
    isDisabledLine: boolean;
}
const props = withDefaults(defineProps<Props>(), {
    modelValue: '',
    multiple: true,
    disabled: false,
    label: '',
    tips: false,
    isDisabledLine: false
});
const stores = reactive<any[]>([]);

const emit = defineEmits(['update:modelValue', 'change']);

const updateValue = (value: any) => {
    emit('update:modelValue', value);
    // emit('change', value)
};

const ZWStoreRef = ref<any>(null);

const show = () => {
    ZWStoreRef.value.visible = true;
};

const submit = (value: any) => {
    stores.splice(0);
    stores.push(...value);
    if (props.multiple) {
        updateValue(mapID(value));
        emit('change', value);
    } else {
        updateValue(value[0]?.id);
        emit('change', value);
    }
};

const handleClose = (item: any, index: number) => {
    stores.splice(index, 1);
    if (props.multiple) {
        updateValue(mapID(stores));
        emit('change', stores);
    } else {
        updateValue(stores[0]?.id ?? '');
        emit('change', stores);
    }
    // DepartRef.value.removeItem(item)
};

const mapID = (arr: any) => {
    if (arr?.length) {
        return arr.map((item: any) => item.id);
    } else {
        return [];
    }
};
</script>
<style scoped lang="scss">
.store_item {
    margin-right: 6px;
}
</style>
